package org.ilc.push.socket;

import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 * @author malongbo
 */
public class SendWorker extends Thread {
    private SocketConnection conn;
    private boolean running=false;

    public SendWorker (SocketConnection conn) {
        this.conn = conn;
    }

    public void startWorker(){
        this.running=true;
        this.start();
    }
    public void stopWorker(){
        this.running=false;

    }

    @Override
    public void run() {
        BufferedReader reader = new BufferedReader (new InputStreamReader (System.in));
        byte[] heartData;
        try {
            while (running) {
                System.out.print ("输入接收用户名：");
                String receiver = reader.readLine ();
//                String receiver = "201202002";
//                System.out.print("输入消息：");
                String msg = "hello " + receiver;
                heartData = createHeartData (receiver, msg.getBytes ().length);
                conn.sendData(heartData,msg.getBytes ());
                try {
                    System.out.println ("send data.....");
                    Thread.sleep(conn.getHeartSleepTime());
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();

        } finally {
            heartData = null;

        }
    }

    byte[] createHeartData(String receiver, int content_length) {
        IHeader header = new Header();
        header.addHeader(IHeader.HEAD_AUTH_USER_KEY, conn.getAuthUser());
        header.addHeader(IHeader.HEAD_AUTH_PWD_KEY, conn.getAuthPwd ());
        header.addHeader ("receiver", receiver);
        header.addHeader(IHeader.HEAD_CONTENT_LENGTH_KEY, content_length+"");
        header.addHeader ("auth-type", conn.getAuthType ());
        header.addHeader ("auth-version", conn.getAuthVersion ());
        
        System.out.println(receiver);

        System.out.println (header.toString ());
        return header.toString().getBytes();
    }
}
